<?php

namespace App\Console\Commands;

use App\Services\GraspService;
use App\Services\WechatService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class CheckCartCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'system:cart';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {

        $data = GraspService::findDzyCart();
        if (!$data) {
            Log::error("获取dzy购物车失败");
            return false;
        }
        Log::info("请求成功");
        //    ix7QDEIK7YbcI3Wrc1hxVBHOELtiFkO6iRWwypCCH_c  书名：{{title.DATA}} 价格：{{price.DATA}} 链接：{{link.DATA}}
        foreach ($data as $d) {
            $title = $d['item']['book']['title'];
            $id = $d['item']['id'];
            if (Cache::has('book_' . $id)) {
                continue;
            }
            Log::info("购物车数据", ['title' => $title, 'type' => $d['type']]);
            if ($d['type'] == 'inStockCartBook') {
                $price = $d['item']['price'] / 100;
                //已到货
                Log::info("到货一件", $d);
                $data = ['title' => $title, 'price' => $price, 'link' => "https://www.duozhuayu.com/cart"];
                WechatService::sendMsg($data);
                Cache::put('book_' . $id, $d, now()->addMinutes(60));
                //锁定前加入购物车
                $bookGoods = $d['item']['book']['goods'][0];
                $carParam = [
                    'condition' => $bookGoods['condition'],
                    'flawFlag' => $bookGoods['flawFlag'],
                    'flawReasons' => $bookGoods['flawReasons'],
                ];
                GraspService::lockAddCart($id, $carParam);
                $lockRet = GraspService::lockDzyGood($id);
                Log::info("锁定商品结果", [$lockRet]);
                if ($lockRet) {
                    $lockMsg = [
                        'title' => '商品锁定成功:' . $title,
                        'price' => $price,
                        'link' => "https://www.duozhuayu.com/cart",
                    ];
                    WechatService::sendMsg($lockMsg);
                }
            }
        }
    }
}
